<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入所属用户ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="计划日期" prop="planDate">
        <el-date-picker clearable
          v-model="queryParams.planDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择计划日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="计划中小目标总数" prop="totalGoals">
        <el-input
          v-model="queryParams.totalGoals"
          placeholder="请输入计划中小目标总数"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="已完成的目标数" prop="completedCount">
        <el-input
          v-model="queryParams.completedCount"
          placeholder="请输入已完成的目标数"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="完成比例" prop="completionRate">
        <el-input
          v-model="queryParams.completionRate"
          placeholder="请输入完成比例"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['wx:plan:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['wx:plan:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['wx:plan:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['wx:plan:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="planList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="所属用户ID" align="center" prop="userId" />
      <el-table-column label="计划日期" align="center" prop="planDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.planDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划中小目标总数" align="center" prop="totalGoals" />
      <el-table-column label="已完成的目标数" align="center" prop="completedCount" />
      <el-table-column label="完成比例" align="center" prop="completionRate" />
      <el-table-column label="当日总结备注" align="center" prop="summaryNote" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['wx:plan:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['wx:plan:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改今日计划对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="planRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="所属用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入所属用户ID" />
        </el-form-item>
        <el-form-item label="计划日期" prop="planDate">
          <el-date-picker clearable
            v-model="form.planDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择计划日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="计划中小目标总数" prop="totalGoals">
          <el-input v-model="form.totalGoals" placeholder="请输入计划中小目标总数" />
        </el-form-item>
        <el-form-item label="已完成的目标数" prop="completedCount">
          <el-input v-model="form.completedCount" placeholder="请输入已完成的目标数" />
        </el-form-item>
        <el-form-item label="完成比例" prop="completionRate">
          <el-input v-model="form.completionRate" placeholder="请输入完成比例" />
        </el-form-item>
        <el-form-item label="当日总结备注" prop="summaryNote">
          <el-input v-model="form.summaryNote" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-divider content-position="center">今日计划子项明细信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAddTodayPlanItem">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="Delete" @click="handleDeleteTodayPlanItem">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="todayPlanItemList" :row-class-name="rowTodayPlanItemIndex" @selection-change="handleTodayPlanItemSelectionChange" ref="todayPlanItem">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="外键：关联 today_plan.id" prop="planId" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.planId" placeholder="请输入外键：关联 today_plan.id" />
            </template>
          </el-table-column>
          <el-table-column label="是否已完成" prop="isCompleted" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.isCompleted" placeholder="请输入是否已完成" />
            </template>
          </el-table-column>
          <el-table-column label="完成时间" prop="completedTime" width="240">
            <template #default="scope">
              <el-date-picker clearable
                v-model="scope.row.completedTime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择完成时间">
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column label="单项备注说明" prop="remark" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.remark" placeholder="请输入单项备注说明" />
            </template>
          </el-table-column>
          <el-table-column label="排序顺序" prop="sortOrder" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.sortOrder" placeholder="请输入排序顺序" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Plan">
import { listPlan, getPlan, delPlan, addPlan, updatePlan } from "@/api/wx/plan"

const { proxy } = getCurrentInstance()

const planList = ref([])
const todayPlanItemList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const checkedTodayPlanItem = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: null,
    planDate: null,
    totalGoals: null,
    completedCount: null,
    completionRate: null,
    summaryNote: null,
  },
  rules: {
    userId: [
      { required: true, message: "所属用户ID不能为空", trigger: "blur" }
    ],
    planDate: [
      { required: true, message: "计划日期不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询今日计划列表 */
function getList() {
  loading.value = true
  listPlan(queryParams.value).then(response => {
    planList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    userId: null,
    planDate: null,
    totalGoals: null,
    completedCount: null,
    completionRate: null,
    summaryNote: null,
    createTime: null,
    updateTime: null
  }
  todayPlanItemList.value = []
  proxy.resetForm("planRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加今日计划"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getPlan(_id).then(response => {
    form.value = response.data
    todayPlanItemList.value = response.data.todayPlanItemList
    open.value = true
    title.value = "修改今日计划"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["planRef"].validate(valid => {
    if (valid) {
      form.value.todayPlanItemList = todayPlanItemList.value
      if (form.value.id != null) {
        updatePlan(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addPlan(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除今日计划编号为"' + _ids + '"的数据项？').then(function() {
    return delPlan(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 今日计划子项明细序号 */
function rowTodayPlanItemIndex({ row, rowIndex }) {
  row.index = rowIndex + 1
}

/** 今日计划子项明细添加按钮操作 */
function handleAddTodayPlanItem() {
  let obj = {}
  obj.planId = ""
  obj.isCompleted = ""
  obj.completedTime = ""
  obj.remark = ""
  obj.sortOrder = ""
  todayPlanItemList.value.push(obj)
}

/** 今日计划子项明细删除按钮操作 */
function handleDeleteTodayPlanItem() {
  if (checkedTodayPlanItem.value.length == 0) {
    proxy.$modal.msgError("请先选择要删除的今日计划子项明细数据")
  } else {
    const todayPlanItems = todayPlanItemList.value
    const checkedTodayPlanItems = checkedTodayPlanItem.value
    todayPlanItemList.value = todayPlanItems.filter(function(item) {
      return checkedTodayPlanItems.indexOf(item.index) == -1
    })
  }
}

/** 复选框选中数据 */
function handleTodayPlanItemSelectionChange(selection) {
  checkedTodayPlanItem.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('wx/plan/export', {
    ...queryParams.value
  }, `plan_${new Date().getTime()}.xlsx`)
}

getList()
</script>
